package com.example.itas;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.example.classes.IP;

public class LoginActivity extends Activity {
	ProgressDialog dialog;

	Button login;
	EditText edt_id, edt_pw;

	private final String TAG = "LoginActivity";

	IP ip = new IP();
	private final String HOST = ip.ip;
	private final int PORT = 8080;
	private final String PATH = "/IServer-war/webresources/entities.userlist/login";

	private MyApplication myApp;
	private SharedPreferences sharedPref;
	private Editor editor;
	private CheckBox checkbox;
	private Boolean check;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		login = (Button) findViewById(R.id.login_btn_ok);
		edt_id = (EditText) findViewById(R.id.login_et_id);
		edt_pw = (EditText) findViewById(R.id.login_et_pw);

		login.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				AsyncLogin al = new AsyncLogin();
				al.execute();

			}
		});

		myApp = (MyApplication) getApplication();
		
		sharedPref = myApp.getSharedPref();
		checkbox = (CheckBox) findViewById(R.id.remember_checkbox);
		check = sharedPref.getBoolean("checkbox", false);
		editor = sharedPref.edit();
		checkbox.setChecked(check);

		if (check) {
			String uid = myApp.getUid();
			String upass = myApp.getUpass();
			edt_id.setText(uid);
			edt_pw.setText(upass);
//			edt_id.setText(sharedPref.getString("edt_id", ""));
		}

	}

//	@Override
//	protected void onStart() {
//		// TODO Auto-generated method stub
//		sharedPref = myApp.getSharedPref();
//		// checkbox = (CheckBox) findViewById(R.id.checkBox1);
//		Boolean check = sharedPref.getBoolean("checkbox", false);
//
//		checkbox.setChecked(check);
//		super.onStart();
//	}
//
//	@Override
//	protected void onDestroy() {
//		// TODO Auto-generated method stub
//		sharedPref = myApp.getSharedPref();
//		// checkbox = (CheckBox) findViewById(R.id.checkBox1);
//		editor.putBoolean("checkbox", checkbox.isChecked());
//
//		editor.commit();
//		super.onDestroy();
//	}
//
//	@Override
//	protected void onResume() {
//		// TODO Auto-generated method stub
//		sharedPref = myApp.getSharedPref();
//		// checkbox = (CheckBox) findViewById(R.id.checkBox1);
//		Boolean check = sharedPref.getBoolean("checkbox", false);
//
//		checkbox.setChecked(check);
//		super.onResume();
//	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
//		sharedPref = myApp.getSharedPref();
		// checkbox = (CheckBox) findViewById(R.id.checkBox1);
		editor.putBoolean("checkbox", checkbox.isChecked());
		editor.commit();
		
		if (!check) {
			myApp.setUid("");
			myApp.setUpass("");
		}
		
		super.onPause();
	}

//	@Override
//	protected void onStop() {
//		// TODO Auto-generated method stub
//		sharedPref = myApp.getSharedPref();
//		// checkbox = (CheckBox) findViewById(R.id.checkBox1);
//		editor.putBoolean("checkbox", checkbox.isChecked());
//
//		editor.commit();
//		super.onStop();
//	}

	private class AsyncLogin extends AsyncTask<String, Void, String> {

		@Override
		protected void onPreExecute() {

			dialog = ProgressDialog.show(LoginActivity.this, "",
					"Now Logging...", true);
		}

		@Override
		protected String doInBackground(String... params) {

			String result = "false";

			// create() method of the web service needs a Person object as input
			String id = edt_id.getText().toString();
			String pwd = edt_pw.getText().toString();
			
			//store user id in the app
			myApp.setUid(id);

			HttpHost target = new HttpHost(HOST, PORT);
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(PATH);

			// set the MIME type for POST message body.
			post.setHeader("Content-Type", "application/x-www-form-urlencoded");

			HttpEntity entity = null;

			List<NameValuePair> idpair = new ArrayList<NameValuePair>();
			idpair.add(new BasicNameValuePair("ID", id));
			idpair.add(new BasicNameValuePair("PWD", pwd));

			try {
				post.setEntity(new UrlEncodedFormEntity(idpair));

				HttpResponse response = client.execute(target, post);

				// Status code 204 is success with "No content".
				// This happens when a RESTful method returns void.
				if (response.getStatusLine().getStatusCode() < 400) {
					result = "get";
				}

				entity = response.getEntity();
				
				String str = EntityUtils.toString(entity);

				// convert JSON to Person
				result = str;

				Log.d(TAG, "" + response.getStatusLine().getStatusCode());
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				Log.i("errorr:", "UnsupportedEncodingException");
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				Log.i("errorr:", "ClientProtocolException");
			} catch (IOException e) {
				e.printStackTrace();
				Log.i("errorr:", "IOException");
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dismiss();

			if (result.equals("YES")) {
				if (check) {
					String uid = edt_id.getText().toString();
					String upass = edt_pw.getText().toString();
					myApp.setUid(uid);
					myApp.setUpass(upass);
				}
				
				Intent i = new Intent(LoginActivity.this, InfoTabActivity.class);
				startActivity(i);
				Toast.makeText(LoginActivity.this, "Login success!",
						Toast.LENGTH_SHORT).show();
			} else if (result.equals("NO")) {
				Toast.makeText(LoginActivity.this, "Check your ID or password",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(LoginActivity.this, "Error!", Toast.LENGTH_SHORT)
						.show();
			}

			// kwanhong
			// if(checkbox.isChecked()){
			// editor.putString("edt_id", edt_id.getText().toString());
			// }

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_login, menu);
		return true;
	}
}
